package com.yunfei.api.upload;

import com.yunfei.api.smrz.bo.AppFileBo;
import com.yunfei.api.upload.contants.UploadContants;
import com.yunfei.api.upload.param.UploadParam;
import com.yunfei.bo.crmAcceDtl.CrmAcceDtlBo;
import com.yunfei.bo.result.ResultModel;
import com.yunfei.enums.ResultStatus;
import com.yunfei.mapper.aiiidb.*;
import com.yunfei.mapper.crm.TblobtSorageMapper;
import com.yunfei.utils.DateUtil;
import com.yunfei.utils.contants.ApplicationConstant;
import com.yunfei.utils.string.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("ALL")
@Controller
@Api(value = "专业投资者认证文件上传",tags = "专业投资者认证文件上传")
public class ZhuanYeTouZiZheUploadImageApiController {
    @Autowired
    private Environment env;
    @Autowired
    private TblobtSorageMapper tblobtSorageMapper;
    @Autowired
    private ShiMingRenZhengUploadMapper shiMingRenZhengUploadMapper;
    @Autowired
    private ZhuanYeTouZiZheRenZhengUploadMapper zhuanYeTouZiZheRenZhengUploadMapper;
    @Autowired
    private CrmAcceDtlMapper crmAcceDtlMapper;
    @Autowired
    private HeGeTouZiZheRenZhengMapper heGeTouZiZheRenZhengMapper;
    /**
    * @Description: 通用图片上传，附件上传接口
    * @Param: uploadType 图片上传类型：
    * @Param: lStorageid 附件ID
    * @Param: pReasonInfo2 实名认证接口返回的pReasonInfo2
     * PROD -产品
     * NEWS -资讯
     * SHOP -商城
     * VIDEO -视频
     * PRODANSW -产品回复
     * CLUB -秀实俱乐部
     * CRM --CRM附件
    * @return: void
    * @Author: zhengyunfei
    * @Date: 2019/1/25
    * @time:10:32
    */
    @RequestMapping(value = "/api/zytzz/upload",method = RequestMethod.POST)
    @Transactional
    @ResponseBody
    @ApiOperation(value = "单文件上传",notes = "单文件上传",position = 1,response = Object.class)
    public ResultModel saveCardPic(HttpServletRequest request, HttpServletResponse response, String uploadType, int index, String pReasonInfo2, String cCustNo){
        ResultModel resultModel=new ResultModel();
        response.setHeader("Access-Control-Allow-Origin", "*");
        String uploadPath = env.getProperty(ApplicationConstant.FILE_IMAGE_PATH);
        String imageDomain = env.getProperty(ApplicationConstant.IMAGE_SERVER_DOMAIN) + "files/";
        String lStorageid=tblobtSorageMapper.getTblobStorageSeq()+"";

        List<AppFileBo> appFileList=new ArrayList<>();
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            // 获得第1张图片（根据前台的name名称得到上传的文件）
            MultipartFile imgFile1 = multipartHttpServletRequest.getFile("file");
                if (!imgFile1.isEmpty()) {
                    //获取前端传来的文件名
                    String fileName = imgFile1.getOriginalFilename();
                    // 设置存放图片文件的路径
                    String today= DateUtil.getToDay();
                    try {
                        Map<String,Object> cCreatroQueryMap=new HashMap<>();
                        cCreatroQueryMap.put("cCustNo",cCustNo);
                        String cCreator=zhuanYeTouZiZheRenZhengUploadMapper.getVCreator(cCreatroQueryMap);
                        AppFileBo appFileBo=new AppFileBo();
                        appFileBo.setlStorageid(lStorageid);
                        appFileBo.setUserId(cCustNo);
                        String fileExt = fileName.substring(fileName.lastIndexOf(".")+1, fileName.length());
                        appFileBo.setcFilename(fileName);//文件名
                        appFileBo.setcFileSize(imgFile1.getSize()+"");//文件大小
                        String prex=lStorageid.substring(0,lStorageid.length()-1);
                        String filePath=uploadPath+uploadType+"/"+today+"/Tblobstorage/"+prex+"/"+appFileBo.getlStorageid()+"."+fileExt;
                        appFileBo.setcFilepath(filePath);
                        try {
                            //利用文件流保存文件
                            File saveFile= new File(filePath);
                            File parentFile=saveFile.getParentFile();
                            if(!parentFile.exists()&&!parentFile.isDirectory()){
                                parentFile.mkdirs();
                            }
                            if(!saveFile.exists())
                            {
                                try {
                                    saveFile.createNewFile();
                                } catch (IOException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }
                            imgFile1.transferTo(saveFile);
                            System.out.println("文件上传路径："+filePath);
                            String appFileName=appFileBo.getlStorageid()+"."+fileExt;
                            String fileUrl = imageDomain  + "/" +today+"/Tblobstorage/"+prex+"/"+appFileName;
                            appFileBo.setFileUrl(fileUrl);
                            appFileBo.setAppFileName(appFileName);
                            System.out.println("文件访问地址=========="+fileUrl);
                            //保存文件到crm数据库
                            appFileBo.setcSubkeyId(pReasonInfo2);
                            Map<String,Object> queryMap=new HashMap<>();
                            queryMap.put("userId",appFileBo.getUserId());
                            String deptNodeCode=shiMingRenZhengUploadMapper.getDeptNodeCode(queryMap);
                            if(StringUtil.isNullOrEmpty(deptNodeCode)){
                                deptNodeCode="";
                            }
                            appFileBo.setDeptNodeCode(deptNodeCode);
                            //实名认证文件处理
                            if(index==0){
                                appFileBo.setcCataLog("TCUSTREGISTERREQ_MAIN");
                                String lStrorageId=shiMingRenZhengUploadMapper.getLstrorageId(appFileBo);
                                appFileBo.setlStorageid(lStrorageId);
                                shiMingRenZhengUploadMapper.insertFirst(appFileBo);
                            }else{
                                appFileBo.setcCataLog("TCUSTREGISTERREQ");
                                shiMingRenZhengUploadMapper.insertSecond(appFileBo);
                            }
                            //保存文件附件到app数据库
                            CrmAcceDtlBo crmAcceDtlBo=new CrmAcceDtlBo();
                            crmAcceDtlBo.setLStorageid(lStorageid);
                            crmAcceDtlBo.setFileUrl(fileUrl);
                            crmAcceDtlMapper.add(crmAcceDtlBo);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } catch (Exception e) {

                    }

                }


        }
        resultModel.setCode(ResultStatus.SUCCESS.getCode());
        resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
        return resultModel;
    }

    @RequestMapping(value = "/api/zytzz/upload2",method = RequestMethod.POST)
    @Transactional
    @ResponseBody
    @ApiOperation(value = "多文件上传",notes = "多文件上传",position = 1,response = Object.class)
    public ResultModel saveCardPic2(HttpServletRequest request, HttpServletResponse response,UploadParam uploadParam){
        ResultModel resultModel=new ResultModel();
        String uploadType=uploadParam.getUploadType();
        if(StringUtil.isNullOrEmpty(uploadType)){
            uploadType= UploadContants.UPLOAD_TYPE_CRM;
        }
        int fileCount=uploadParam.getFileCount();
        String pReasonInfo2=uploadParam.getpReasonInfo2();
        String cCustNo=uploadParam.getcCustNo();
        response.setHeader("Access-Control-Allow-Origin", "*");
        String uploadPath = env.getProperty(ApplicationConstant.FILE_IMAGE_PATH);
        String imageDomain = env.getProperty(ApplicationConstant.IMAGE_SERVER_DOMAIN) ;
        List<AppFileBo> appFileList=new ArrayList<>();
        String lStorageidArray[]=new String[fileCount];
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            Map<String,Object> cCreatroQueryMap=new HashMap<>();
            cCreatroQueryMap.put("cCustNo",cCustNo);
            String vCreator=zhuanYeTouZiZheRenZhengUploadMapper.getVCreator(cCreatroQueryMap);
            // 获得第1张图片（根据前台的name名称得到上传的文件）
            for(int i=0;i<fileCount;i++){
                List<MultipartFile> imgFileList = multipartHttpServletRequest.getFiles("file");
                MultipartFile imgFile1=multipartHttpServletRequest.getFile("file"+i);
                String lStorageid=tblobtSorageMapper.getTblobStorageSeq()+"";
                System.out.println("id"+i+"==================================="+lStorageid);
                if (!imgFile1.isEmpty()) {
                    //获取前端传来的文件名
                    String fileName = imgFile1.getOriginalFilename();
                    // 设置存放图片文件的路径
                    String today= DateUtil.getToDay();
                    try {

                        AppFileBo appFileBo=new AppFileBo();
                        appFileBo.setlStorageid(lStorageid);
                        appFileBo.setUserId(cCustNo);
                        appFileBo.setvCreator(vCreator);
                        String fileExt = fileName.substring(fileName.lastIndexOf(".")+1, fileName.length());
                        appFileBo.setcFilename(fileName);//文件名
                        appFileBo.setcFileSize(imgFile1.getSize()+"");//文件大小
                        String prex=lStorageid.substring(0,lStorageid.length()-1);
                        String filePath=uploadPath+uploadType+"/"+today+"/Tblobstorage/"+prex+"/"+appFileBo.getlStorageid()+"."+fileExt;
                        appFileBo.setcFilepath(filePath);
                        try {
                            //利用文件流保存文件
                            File saveFile= new File(filePath);
                            File parentFile=saveFile.getParentFile();
                            if(!parentFile.exists()&&!parentFile.isDirectory()){
                                parentFile.mkdirs();
                            }
                            if(!saveFile.exists())
                            {
                                try {
                                    saveFile.createNewFile();
                                } catch (IOException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }
                            imgFile1.transferTo(saveFile);
                            System.out.println("文件上传路径："+filePath);
                            String appFileName=appFileBo.getlStorageid()+"."+fileExt;
                            String fileUrl = imageDomain  + "/"+uploadType+"/" +today+"/Tblobstorage/"+prex+"/"+appFileName;
                            appFileBo.setFileUrl(fileUrl);
                            appFileBo.setAppFileName(appFileName);
                            System.out.println("文件访问地址=========="+fileUrl);
                            //保存文件到crm数据库
                            appFileBo.setcSubkeyId(pReasonInfo2);
                            Map<String,Object> queryMap=new HashMap<>();
                            queryMap.put("userId",appFileBo.getUserId());
                            String deptNodeCode=shiMingRenZhengUploadMapper.getDeptNodeCode(queryMap);
                            if(StringUtil.isNullOrEmpty(deptNodeCode)){
                                deptNodeCode="";
                            }
                            appFileBo.setDeptNodeCode(deptNodeCode);
                            //专业投资者认证文件处理
                            zhuanYeTouZiZheRenZhengUploadMapper.insert(appFileBo);
                            //保存文件附件到app数据库
                            CrmAcceDtlBo crmAcceDtlBo=new CrmAcceDtlBo();
                            crmAcceDtlBo.setLStorageid(lStorageid);
                            crmAcceDtlBo.setFileUrl(fileUrl);
                            crmAcceDtlBo.setcCustNo(cCustNo);
                            crmAcceDtlMapper.add(crmAcceDtlBo);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } catch (Exception e) {

                    }

                }
            }

        }
        resultModel.setCode(ResultStatus.SUCCESS.getCode());
        resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
        return resultModel;
    }


}
